package com.cxyd.modules.job.task.tcpTask;

import com.cxyd.common.utils.ApiResult;
import com.cxyd.modules.job.utils.TcpClient;
import com.cxyd.modules.wcs.dto.PostTcpDTO;
import com.cxyd.modules.wcs.dto.PostWmsDTO;
import com.cxyd.modules.wcs.dto.TcpIpDTO;
import com.cxyd.modules.wcs.entity.UrlMappingEntity;
import com.cxyd.modules.wcs.service.PostTcpService;
import com.cxyd.modules.wcs.service.TcpIpService;
import com.cxyd.modules.wcs.service.UrlMappingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component("post-tcp")
@Slf4j
public class PostTcpTask {
    @Resource
    private PostTcpService postTcpService;
    @Resource
    private TcpIpService tcpIpService;
    @Resource
    private UrlMappingService urlService;
    @Resource
    private RestTemplate restTemplate;

    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public void scanPostTcp() {
        lock.lock();
        try {
//            优先获取一下代POST的信息
            PostTcpDTO postTcp = postTcpService.getPostTcp();
            if (postTcp == null) {
//                log.info("no post-tcp to send...");
                return;
            }
            log.info("获取到待上报指令：{}", postTcp);
            UrlMappingEntity url_wms = urlService.getUrlByNo("WMS_TCP_URL");
            if (url_wms == null || url_wms.getUrlAdr().isEmpty()) {
                log.info("[WMS_TCP_URL]未配置!");
                return;
            }
            ApiResult respond = restTemplate.postForObject(url_wms.getUrlAdr(), postTcp, ApiResult.class);
            if (respond == null) {
                log.error("上位系统无响应!");
                return;
            }
            log.info("[wcs_post_tcp]指令交互成功，response:{}", respond);
//            收到反馈则处理反馈信息
            postTcpService.postTcpHandle(postTcp, respond.toString());
        } catch (Exception e) {
            log.error("指令下发失败", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
